<?php 
hd_core::load_class('init', 'admin');
class admin_control extends init_control {
	public function _initialize() {
		parent::_initialize();
		$this->menu = model('wxmenu','service');
		$this->weixin_service = model('weixin','service');
	}
	
	public function index(){		
		include $this->admin_tpl('config_index');
	}
	
	public function add(){
		if(checksubmit('dosubmit')){
			$result = $this->menu->add($_GET);
			if(!$result){
				showmessage($this->menu->error);
			}else{
				showmessage('操作成功',url('weixin/admin/menu'),1);
			}
		}else{
			include $this->admin_tpl('wxmenu_edit');
		}
	}
	
	public function edit(){
		if(checksubmit('dosubmit')){
			$result = $this->menu->edit($_GET);
			if(!$result){
				showmessage($this->menu->error);
			}else{
				showmessage('操作成功',url('weixin/admin/menu'),1);
			}
		}else{
			$info = $this->menu->get_category_by_id($_GET['id']);
			include $this->admin_tpl('wxmenu_edit');
		}
	}
	
	public function delete(){
		$result = $this->menu->delete($_GET);
		if(!$result){
			showmessage($this->menu->error);
		}
		showmessage('操作成功',url('weixin/admin/menu'),1);
	}
	
	public function menu_choose(){
		$menu_list = $this->menu->get_menu_tree();
		include $this->admin_tpl('wxmenu_choose');
	}
	
	public function create_menu(){		
		$AppId = AppId;
		$AppSecret = AppSecret;
		
		if (!trim($AppId)) {
			showmessage('请填写微信AppId',url('weixin/admin/menu'),1);
        }
        if (!trim($AppSecret)) {
			showmessage('请填写微信AppSecret',url('weixin/admin/menu'),1);
        }
		
		if(trim($AppId) && trim($AppSecret)){
			$ACCESS_LIST = $this->menu->curl($AppId, $AppSecret); //获取到的凭证
			
			if ($ACCESS_LIST['access_token'] != '') {
				$access_token = $ACCESS_LIST['access_token']; //获取到ACCESS_TOKEN
				$data = $this->menu->get_menu_list(0);
				$msg = $this->menu->curl_menu($access_token, preg_replace("#\\\u([0-9a-f]+)#ie", "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))", $data));
			} else {
				showmessage('创建失败,微信AppId或微信AppSecret填写错误',url('weixin/admin/menu'),1);
			}
		}else{
			$msg['errmsg'] = 'ok';
		}		
		if($msg['errmsg'] == 'ok'){
			showmessage('创建自定义菜单成功',url('weixin/admin/menu'),1);
		}else{
			showmessage('创建微信自定义菜单失败!,错误提示：'.$this->weixin_service->errInfo($msg['errcode']).'',url('weixin/admin/menu'),1);
		}
	}
	
	private function menuResponseParse($content,$method='get') {
		$datas = @json_decode(mb_convert_encoding($content,"GBK","UTF-8"),true);
		if(!is_array($datas)) {
			return $this->error(-1, '接口调用失败，请重试！' . (is_string($content) ? "支付宝公众平台返回元数据: {$content}" : ''));
		}
		$dat=$datas["alipay_mobile_public_menu_{$method}_response"];
		if(is_array($dat) && $dat['code'] == '200') {
			return $this->error('ok');
		} else {
			if(is_array($dat)) {
				return $this->error(-1, "支付宝公众平台返回接口错误. \n错误代码为: {$dat['code']} \n错误信息为: {$dat['msg']}");
			} else {
				return $this->error(-1, '支付宝公众平台未知错误');
			}
		}
	}
	
	public function error($errno, $message = '') {
		return array(
			'errmsg' => $errno,
			'message' => $message,
		);
	}
	
	private function bulidMenuPostData($method, $bizcontent, $config){
		require_once(APP_PATH . 'library/fuwu/AlipaySign.php');
		$paramsArray = array (
				'method' => $method,
				'sign_type' => 'RSA',
				'app_id' => $config['app_id'],
				'timestamp' => date ( 'Y-m-d H:i:s', time () ) 
		);
		if($bizcontent){
			$paramsArray['biz_content']=$bizcontent;
		}
		$as = new AlipaySign();
		$sign = $as->sign_request( $paramsArray, $config ['merchant_private_key_file'] );
		$paramsArray['sign'] = $sign;
		return $paramsArray;
	}
	
	public function menu(){
		$sqlmap = array();
		$sqlmap['pid'] = 0;
		$_GET['limit'] = isset($_GET['limit']) ? $_GET['limit'] : 10;
		$category = model('wxmenu')->where($sqlmap)->page($_GET['page'])->limit($_GET['limit'])->order("sort DESC")->select();
        $count = model('wxmenu')->where($sqlmap)->count();
        $pages = $this->admin_pages($count,$_GET['limit']);
		include $this->admin_tpl('wxmenu_index');
	}
	
        public function wx(){
            $sqlmap = array();
            $_GET['limit'] = isset($_GET['limit']) ? $_GET['limit'] : 10;
            $wx = model('wxconfig')->where($sqlmap)->page($_GET['page'])->limit($_GET['limit'])->order("id DESC")->select();
            $count = model('wxconfig')->where($sqlmap)->count();
            $pages = $this->admin_pages($count,$_GET['limit']);
            include $this->admin_tpl('wx_list');
	}
        
        public  function wxadd(){
            if(checksubmit('dosubmit')){
                $data = array();
		$data['name'] = $_GET['name'];
		$data['url'] = $_GET['url'];
		$data['token'] = $_GET['token'];
		$data['appid'] = $_GET['appid'];
		$data['appsecret'] = $_GET['appsecret'];
		$result = model('wxconfig')->update($data);
                if(!$result){
                        showmessage("操作失败");
                }else{
                        showmessage('操作成功',url('weixin/admin/wx'),1);
                }
            }else{
                $info = [];
                $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
                for ($i = 0; $i < 32; $i++) {
                        $info['token'] .= $chars[mt_rand(0, strlen($chars) - 1)];
                }
                
                include $this->admin_tpl('wx_edit');
            }
        }
        
        public function wxedit(){
            if(checksubmit('dosubmit')){
                    $data['name'] = $_GET['name'];
                    $data['url'] = $_GET['url'];
                    $data['token'] = $_GET['token'];
                    $data['appid'] = $_GET['appid'];
                    $data['appsecret'] = $_GET['appsecret'];
                    $result = model('wxconfig')->where(['id'=>$_GET['id']])->save($data);
                    if(!$result){
                            showmessage("操作失败");
                    }else{
                            showmessage('操作成功',url('weixin/admin/wx'),1);
                    }
            }else{
                    $info = model('wxconfig')->find($_GET['id']);
                    include $this->admin_tpl('wx_edit');
            }
	}
        public function wxdelete(){
            $data = array();
            $data['id'] = array('IN', $_GET['id']);
            $result = model('wxconfig')->where($data)->delete();
            if(!$result){
                    showmessage("操作失败");
            }
            showmessage('操作成功',url('weixin/admin/wx'),1);
	}
	public function ajax_son_class(){
		$result = $this->menu->ajax_son_class($_GET);		
		if(!$result){
			showmessage($this->menu->error,'',0,'','json');
		}else{
			showmessage('操作成功','',1,$result,'json');
		}
	}
	
	public function ajax_edit(){
		$result = $this->menu->ajax_edit($_GET);
		if(!$result){
			showmessage($this->menu->error);
		}else{
			showmessage('操作成功','',1);
		}
	}

    /**
     * [index 保险列表]
     */
	public function safest()
    {
        $sqlmap = array();
        $_GET['limit'] = isset($_GET['limit']) ? $_GET['limit'] : 10;
        $article = model('safest')->where($sqlmap)->page($_GET['page'])->limit($_GET['limit'])->select();
        foreach($article as $key => $value){
            $article[$key]['dataline'] = date('Y-m-d H:i:s',$value['time']);
        }
        $count = model('safest')->where($sqlmap)->count();
        $pages = $this->admin_pages($count, $_GET['limit']);
        include $this->admin_tpl('safest_index');
    }
    /**
     * [保险删除]
     */
    public function delete_safest()
    {
        $result = model('safest')->where(array('id'=>$_GET['id']))->delete();
        if(!$result){
            showmessage('操作失败',url('weixin/admin/safest'),1);
        }
        showmessage('操作成功',url('weixin/admin/safest'),1);
    }
    /**
     * [保险编辑]
     */
    public function edit_safest(){
        $info= model('safest')->where(array('id'=>$_GET['id']))->find();
        if(IS_POST){
            $_POST['stime'] = $info['stime'];
            $_POST['etime'] = $info['etime'];
            $_POST['time'] = time();
            $date = $_POST;
            $result = model('safest')->update($date);
            if(!$result){
                showmessage('操作失败',url('weixin/admin/safest'));
            }else{
                showmessage('操作成功',url('weixin/admin/safest'));
            }
        }else{
            include $this->admin_tpl('edit_safest');
        }
    }
	
	public function send(){
		if(IS_POST){			
			$openid = model('member')->where(array('group_id'=>intval($_POST['type']),'openid'=>array('neq','')))->getField('openid',true);
			if(count($openid) > 0){
				if(count($openid) > 1){
					$openid = $openid;
				}else{
					$openid = $openid[0];
				}
				$this->setting = model('admin/setting', 'service')->get();			
				$content = trim($_POST['content']);
				$wechat = new weixin();
				$data = array(
					"touser" => $openid, 
					"msgtype" => "text",
					"text" => array(
						'content' => urlencode($content)       
					)
				);			
				
				if(count($openid) > 1){
					$wechat->sendMessage($data);	
				}else{
					$wechat->send($data);
				}
				showmessage('发送成功',url('weixin/admin/send'));
			}
		}else{
            include $this->admin_tpl('send');
        }
	}
}